//
//  ExpressController.m
//  EagleEye
//
//  Created by 18_李明明 on 15-1-20.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "ExpressController.h"
#import "CompanyController.h"
#import "NetHander.h"
#import "ExpressTableViewCell.h"
#import "DataBaseHandler.h"
@interface ExpressController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITextField *expressNumber;
@property (nonatomic, strong) NSString *companyPinyin;
@property (nonatomic, strong) UITableView *contentTableView;
@property (nonatomic, strong) NSArray *arr;
@property (nonatomic, strong) UIButton *company;
@property (nonatomic, strong) DataBaseHandler *dataBase;
@end

@implementation ExpressController
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.arr = [NSArray array];
        self.companyPinyin = [NSString string];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"快递查询";
    self.dataBase = [DataBaseHandler shareInstance];
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(targetCancle:)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"cancle.png"] style:UIBarButtonItemStylePlain target:self action:@selector(targetCancle:)];
    [self handleData];
}
// 返回按钮
- (void)targetCancle:(UIButton *)cancle{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)handleData
{
    // 创建一个选择快递公司的按钮
    self.company = [UIButton buttonWithType:UIButtonTypeSystem];
    self.company.frame = CGRectMake(10, 0, 120, 40);
    [self.company setTitle:@"选择快递公司" forState:UIControlStateNormal];
    [self.company addTarget:self action:@selector(targetCompany:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.company];
    // 创建一个输入快递号的输入框
    self.expressNumber = [[UITextField alloc] initWithFrame:CGRectMake(10, 50, WIDTH - 20, 40)];
    self.expressNumber.placeholder = @"请输入快递号";
    if (self.selectedCompany.length != 0) {
        [self.company setTitle:self.selectedCompany forState:UIControlStateNormal];
        self.expressNumber.text = self.selectedNumber;
        self.companyPinyin = self.selectedPinyin;
        NSLog(@"2%@", self.selectedPinyin);
        [self resolveData];
    }
    self.expressNumber.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:self.expressNumber];
    // 创建一个开始查询的按钮
    UIButton *query = [UIButton buttonWithType:UIButtonTypeSystem];
    query.frame = CGRectMake(10, 100, 60, 40);
//    query.backgroundColor = [UIColor cyanColor];
    [query setTitle:@"查询" forState:UIControlStateNormal];
    [self.view addSubview:query];
    [query addTarget:self action:@selector(targetQuery:) forControlEvents:UIControlEventTouchUpInside];
    // 创建tableview
    self.contentTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 150, WIDTH, HEIGHT - 220) style:UITableViewStyleGrouped];
    self.contentTableView.dataSource = self;
    self.contentTableView.delegate =self;
    [self.view addSubview:self.contentTableView];
}
// 选择公司按钮事件，并接受下一页传来的的值
- (void)targetCompany:(UIButton *)button
{
    CompanyController *com = [[CompanyController alloc] init];
    [com setSelect:^(NSString *company, NSString *company1) {
        self.companyPinyin = company;
        [button setTitle:company1 forState:UIControlStateNormal];
    }];
    [self.navigationController pushViewController:com animated:YES];
}
// 查询按钮事件
- (void)targetQuery:(UIButton *)button
{
    if (self.expressNumber.text.length == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"查询内容不能为空" delegate:self cancelButtonTitle:@"cancle" otherButtonTitles:@"OK", nil];
    }
    [self.expressNumber resignFirstResponder];
    [self.dataBase openDB];
    [self.dataBase createExpress];
    [self.dataBase insertExpress:self.expressNumber.text Company:self.company.titleLabel.text pinyin:self.companyPinyin];
    NSLog(@"1%@", self.companyPinyin);
    [self resolveData];
}
// 解析数据
- (void)resolveData
{
    NSString *str = [NSString stringWithFormat:@"http://apix.sinaapp.com/express/?appkey=liming5712ou&company=%@&number=%@", self.companyPinyin, self.expressNumber.text];
    NSLog(@"%@", str);
    [NetHander getDataWithUrl:str completion:^(NSData *data) {
        // 解析出来后，数据位字符串
        NSString *expressContent = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        if ([expressContent hasPrefix:@"2"]) {
            
            self.arr = [expressContent componentsSeparatedByString:@"\n"];
            //        NSLog(@"%@", self.arr);
        }else{
            self.arr = @[@"您输入的快递号不正确，请核对后在查询！"];
        }
        [self.contentTableView reloadData];
        
    }];
}
// tableview协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr.count;
}
// section
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return @"快递信息";
}
// 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 88;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ExpressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"0502"];
    if (cell == nil) {
        cell = [[ExpressTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"0502"];
    }
    cell.content.text = [self.arr objectAtIndex:indexPath.row];
    return cell;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.expressNumber resignFirstResponder];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
